# -*- coding: utf-8 -*-
"""
Created on Mon Sep 19 16:14:09 2011

@author: sanchez
"""
from PyQt4.QtGui import QMainWindow, QSplitter
from PyQt4.QtCore import SIGNAL

from guidata.dataset.datatypes import DataSet, BeginGroup, EndGroup
from guidata.dataset.dataitems import (FloatItem, IntItem, BoolItem, ChoiceItem,
                             MultipleChoiceItem, ImageChoiceItem, FilesOpenItem,
                             StringItem, TextItem, ColorItem, FileSaveItem,
                             FileOpenItem, DirectoryItem, FloatArrayItem,
                             DateItem, DateTimeItem)

from guidata.qthelpers import create_action, add_actions, get_std_icon


import numpy as np
import scipy as sc
from numpy import sin
from scipy import pi
import os.path


import guidata.dataset.datatypes as dt
import guidata.dataset.dataitems as di
# Local test import:

import tempfile
TEMPDIR = tempfile.mkdtemp(prefix="tmp_")
FILE_MAT = tempfile.NamedTemporaryFile(suffix=".mat", dir=".")

from modreststate import *


import matplotlib
from matplotlib.pyplot import axes
from matplotlib.pyplot import clf
from matplotlib.pyplot import close
from matplotlib.pyplot import figure
from matplotlib.pyplot import grid
from matplotlib.pyplot import plot
from matplotlib.pyplot import savefig
from matplotlib.pyplot import show
from matplotlib.pyplot import subplot
from matplotlib.pyplot import title
from matplotlib.pyplot import xlabel
from matplotlib.pyplot import ylabel
from matplotlib.pyplot import imshow
from matplotlib.pyplot import subplots_adjust
from matplotlib.pyplot import  rc
from matplotlib.pyplot import  grid

#import pylab as plt
matplotlib.rc('text', usetex=False) # True= postscript
matplotlib.rc('font',**{'family':'serif','serif':['Times']})
matplotlib.rc('xtick', labelsize=9)
matplotlib.rc('ytick', labelsize=9)
matplotlib.rc('lines', linewidth=0.5)
matplotlib.rc('lines', color="r")


#--------------------------------------------------
#           structure de donnees
#--------------------------------------------------
class Tdata():
    filename =""   # fichier de donnees brutes .MAT
    prefixe ="" #  prefixe pour sauvegarde

class TsignalParameters():
    nbchannel=0   # nb. de canaux d'acquisition
    nbblock=0     # nb. essais consecutif
    blocksize=10000   # taille d un block d essai
    voies=[]      # matrice de toutes les voies, tous les blocks
    voies_=[]      # matrice de toutes les voies traitees, tous les blocks
    srate=2500       #frequence echantillonnage
    dt=1./srate          # periode echantillonnage
    temps=[]      # axe des temps remis en forme pour un block
    t_sav=[]       # sauvegarde du temps d un block
    ThresholdBeforeTMS=20 # seuil avant TMS en ms
    ThresholdAfterTMS=30   # seuil apres TMS en ms
    numvoie=17           # voie a etudie
    voie_analyse=[]      # 1 voie a analyser parmi toutes les voies originale
    voie_analyse_=[]      # 1 voie a analyser parmi toutes les voies traitee
    deltaBeforeTMS =300       # selection bloc avant la TMS temps en ms
    deltaAfterTMS=1200       # selection bloc apres la TMS  temps en ms
    M_BeforeTMS=[]              # Matrice de donnees avant TMS
    t_BeforeTMS=[]              # temps correspondant avant TMS
    ind0_BeforeTMS=0            # indice de coupure min avant TMS
    ind1_BeforeTMS=0            # indice de coupure max avant TMS
    t0_BeforeTMS=0              # temps de coupure min avant TMS
    t1_BeforeTMS=0              # temps de coupure max avant TMS
    M_AfterTMS=[]              # Matrice de donnees apres TMS
    t_AfterTMS=[]              # temps correspondant apres TMS
    ind0_AfterTMS=0            # indice de coupure min apres TMS
    ind1_AfterTMS=0            # indice de coupure max apres TMS
    t0_AfterTMS=0              # temps de coupure min apres TMS
    t1_AfterTMS=0              # temps de coupure max apres TMS
    alphamin=8.0                # fresquence coupure basse des alphas
    alphamax=14.0     # fresquence coupure haute des alphas
    nbpFFT=2048         # nb. pt. FFT
    freq_visu=100  # 100 Hz frequence de visu à droite
    freq_BeforeTMS=[]  # axe des frequences avant TMS
    M_FFT_BeforeTMS=[]     # modules des FFT pour une voie avant TMS
    freq_AfterTMS=[]  # axe des frequences apres TMS
    M_FFT_AfterTMS =[]    # modules des FFT pour une voie apres TMS
    bn = []             # coef. filtre passe-bande
    Ti_BeforeTMS=250   # temps de reference avant la TMS en ms
    fe_BeforeTMS=10  # freq. etude avant TMS en Hz

class Tondelette():
    f_start=5.
    f_stop=50.
    deltafreq = 0.5
    WSUM_BeforeTMS=[]       # somme des ondelettes pour un canal , tous les blocs
    WSUM_AfterTMS=[]
    ref_phi_BeforeTMS=[]    # sauvegarde des phase avant TMS pour tri pour toutes les voies/tous les blocs
    index_phase=[]          # index trié par rapport aux phases pour toutes les voies
    ITC_BeforeTMS=[]        # tableau des ITCs avant TMS
    ITC_AfterTMS=[]         # tableau des ITCs apres TMS
#--------------------------------------------------
#           classes de dialogue guidata
#--------------------------------------------------
class TFileParameter(dt.DataSet):
    """Selection fichier Matlab"""
    fnames = FilesOpenItem("Open files", "mat", FILE_MAT.name)

class TThreshold(dt.DataSet):
    """Seuil avant et apres TMS"""
    ThresholdBeforeTMS = di.IntItem("Threshold before TMS [ms]", min=1, max=100, default=10)
    ThresholdAfterTMS = di.IntItem("Threshold after TMS [ms]", min=1, max=100, default=20)

class TChannelParameter(dt.DataSet):
    """Channel Parametres"""
    channel= di.IntItem("Channel", min=0, max=63, default=17)
    Ti_BeforeTMS= di.IntItem("Temps de reference avant TMS", min=20, max=2000, default=250)
    Ti_AfterTMS= di.IntItem("Temps de reference apres TMS", min=20, max=2000, default=100)
    fe_BeforeTMS = di.FloatItem("Freq. etude avant TMS. [Hz]", min=1.0, max=1000.0, default=10.0)

class Tdelta(dt.DataSet):
    """selection plage avant et apres TMS"""
    deltaBeforeTMS = di.IntItem("delta before TMS [ms]", min=1, max=2000, default=300)
    deltaAfterTMS = di.IntItem("delta after TMS [ms]", min=1, max=2000, default=1200)

class TParamOndelette(dt.DataSet):
    f_start = di.FloatItem("Freq. min. [Hz]", min=1.0, max=1000.0, default=5.0)
    f_stop = di.FloatItem("Freq. max. [Hz]", min=1.0, max=1000.0, default=50.0)
    deltafreq = di.FloatItem("Delta Freq. [Hz]", min=0.1, max=10.0, default=0.5)

class Tfilter(dt.DataSet):
    """Channel Parametres"""
    AlphaMin = di.FloatItem("Freq. min. [Hz]", min=1.0, max=1000.0, default=8.0)
    AlphaMax = di.FloatItem("Freq. max. [Hz]", min=1.0, max=1000.0, default=14.0)

class Tfft(dt.DataSet):
    nbpFFT = di.IntItem("Nb. pt. FFT", min=256, max=8192, default=2048)
    freq_visu = di.IntItem("freq. visu", min=1, max=1200, default=30)

#--------------------------------------------------
#           Fenetre principale
#--------------------------------------------------
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setWindowTitle("PyrestState")
        self.resize(350, 200)
#--------------------------------------------------
#           Fichiers_menu
#--------------------------------------------------
        Fichiers_menu = self.menuBar().addMenu("Fichiers")
        Traitements_menu = self.menuBar().addMenu("Traitements")
        Visualisations_menu = self.menuBar().addMenu("Visualisations")
        Batch_menu = self.menuBar().addMenu("Batch")
        About_menu = self.menuBar().addMenu("About")


        Ouvrir_action = create_action(self,"Ouvrir",triggered=self.on_open_Fichiers_Ouvrir)
        Quitter_action = create_action(self,"Quitter",triggered=self.on_open_Fichiers_Quitter)

        add_actions(Fichiers_menu,(
        Ouvrir_action,
        Quitter_action,
        ))
#--------------------------------------------------
#           Traitements_menu
#--------------------------------------------------
        Select_voie_action = create_action(self,"Select. voies",triggered=self.on_open_Traitements_Select_voie)
        Artefact_action = create_action(self,"Artefact",triggered=self.on_open_Traitements_Artefact)
        Creation_blocks_action = create_action(self,"Creation blocks",triggered=self.on_open_Traitements_Creation_blocks)
        Filtre_action = create_action(self,"Filtre",triggered=self.on_open_Traitements_Filtre)
        FFT_action = create_action(self,"FFT",triggered=self.on_open_Traitements_FFT)
        ICA_action = create_action(self,"ICA",triggered=self.on_open_Traitements_ICA)
        Ondelette_action = create_action(self,"Ondelette",triggered=self.on_open_Traitements_Ondelette)
        ITC_action = create_action(self,"ITC",triggered=self.on_open_Traitements_ITC)
        Correlation_action = create_action(self,"Correlation",triggered=self.on_open_Traitements_Correlation)

        add_actions(Traitements_menu,(
        Select_voie_action,
        Artefact_action,
        Creation_blocks_action,
        Filtre_action,
        FFT_action,
        ICA_action,
        Ondelette_action,
        ITC_action,
        Correlation_action,
        ))
#--------------------------------------------------
#           Visualisations_menu
#--------------------------------------------------
        Original_action = create_action(self,"Original",triggered=self.on_open_Visualisations_Original)
        Traitees_action = create_action(self,"Traitees",triggered=self.on_open_Visualisations_Traitees)
        Visu_Block_action = create_action(self,"Blocs",triggered=self.on_open_Visualisations_Block)
        FFT_action = create_action(self,"FFT",triggered=self.on_open_Visualisations_FFT)
        ICA_action = create_action(self,"ICA",triggered=self.on_open_Visualisations_ICA)
        Ondelette_action = create_action(self,"Ondelette",triggered=self.on_open_Visualisations_Ondelette)
        ITC_action = create_action(self,"ITC",triggered=self.on_open_Visualisations_ITC)
        Correlation_action = create_action(self,"Correlation",triggered=self.on_open_Visualisations_Correlation)

        add_actions(Visualisations_menu,(
        Original_action,
        Traitees_action,
        Visu_Block_action,
        FFT_action,
        ICA_action,
        Ondelette_action,
        ITC_action,
        Correlation_action,
        ))

#--------------------------------------------------
#           Batch_menu
#--------------------------------------------------
        Originaux_action = create_action(self,"Originaux",triggered=self.on_open_Batch_Originaux)
        Filtre_action = create_action(self,"Filtre",triggered=self.on_open_Batch_Filtre)
        FFT_action = create_action(self,"FFT",triggered=self.on_open_Batch_FFT)
        Ondelette_action = create_action(self,"Ondelette",triggered=self.on_open_Batch_Ondelette)
        tri_Phase_action = create_action(self,"Phase",triggered=self.on_open_Batch_tri_Phase)
        ITC_action = create_action(self,"ITC",triggered=self.on_open_Batch_ITC)

        add_actions(Batch_menu,(
        Originaux_action,
        Filtre_action,
        FFT_action,
        Ondelette_action,
        tri_Phase_action,
        ITC_action,
        ))



#--------------------------------------------------
#           About_menu
#--------------------------------------------------

        Struct_data_action = create_action(self,"Struct. Data",triggered=self.on_open_About_Struct_data)
        Struct_Signal_action = create_action(self,"Struct. Signal",triggered=self.on_open_About_Struct_Signal)

        add_actions(About_menu,(
        Struct_data_action,
        Struct_Signal_action,
        ))


    def on_open_Fichiers_Ouvrir(self):
    #-----------------------------------------------------------------------------
    #    selection du fichier matlab .MAT
    #-----------------------------------------------------------------------------
        f = TFileParameter()
        if f.edit():
            data.filename=list(f.fnames)
            data.filename=data.filename[0]
            data.prefixe = '.'.join(data.filename.split('.')[:-1])
            s=str(data.prefixe)
            s=s.split("\\")
            N=len(s)
            data.prefixe = s[N-1]
            print data.prefixe
        else:
            exit(1)   # pas de fichier selectionne
            return
    #-----------------------------------------------------------------------------
    #    lecture des donnees brutes
    #-----------------------------------------------------------------------------
        SP.nbchannel,SP.nbblock,SP.blocksize,SP.voies,SP.srate, SP.dt=mat2pydata(data.filename)
        SP.nbblock=int(SP.nbblock)
        SP.blocksize=int(SP.blocksize)
        SP.srate=float(SP.srate[0][0]) #liste de liste en float
        print " 1 bnb channel=", SP.nbchannel,"nb block=", SP.nbblock, "bock size=", SP.blocksize," s. rate=",SP.srate
    #-----------------------------------------------------------------------------
    #   axe  des temps TMS au centre
    #-----------------------------------------------------------------------------
        SP.temps=CreatTimeTMS(SP.blocksize,SP.srate)      # creation axe des temps
        SP.t_sav=SP.temps.copy()                          # sauvegarde axe des temps


    def on_open_Fichiers_Quitter(self):
        window.close()
        return

    def on_open_Traitements_Artefact(self):
    #-----------------------------------------------------------------------------
    #   supprime artefact
    #-----------------------------------------------------------------------------
        p= TThreshold()
        if p.edit():
            SP.ThresholdBeforeTMS=p.ThresholdBeforeTMS*1e-3 #en ms
            SP.ThresholdAfterTMS=p.ThresholdAfterTMS*1e-3
        else:
            exit(2)
            return
    #-----------------------------------------------------------------------------
    #     supprime artefac sur toute les voies
    #-----------------------------------------------------------------------------
        SP.voies_=SP.voies.copy()  # copie pour garder la meme taille
        for num in range(SP.nbchannel):
            tmp=SP.voies[num,:,:]  # recupere la voie a etudier
            tmp=tmp.transpose()
            tmp=raz_artefact(SP.temps,tmp,SP.ThresholdBeforeTMS,SP.ThresholdAfterTMS,SP.srate) # supprime artefact
            SP.voies_[num,:,:]=tmp.transpose() #reforme la matrice
            print ".",
        return


    def on_open_Traitements_Creation_blocks(self):
    #-----------------------------------------------------------------------------
    #   Selection des intervalles d etude
    #-----------------------------------------------------------------------------
        p= Tdelta()
        if p.edit():
            SP.deltaBeforeTMS=p.deltaBeforeTMS*1e-3
            SP.deltaAfterTMS=p.deltaAfterTMS*1e-3
        else:
            exit(3)
    #-----------------------------------------------------------------------------
    #     selection block avant TMS
    #-----------------------------------------------------------------------------
        SP.M_BeforeTMS,SP.t_BeforeTMS, SP.ind0_BeforeTMS, SP.ind1_BeforeTMS, \
            SP.t0_BeforeTMS, SP.t1_BeforeTMS=BlockBeforeTMS(SP.voies_,\
            SP.numvoie,SP.blocksize,SP.srate,SP.temps,SP.ThresholdBeforeTMS,SP.deltaBeforeTMS)
        SP.M_AfterTMS,SP.t_AfterTMS, SP.ind0_AfterTMS, SP.ind1_AfterTMS, \
        SP.t0_AfterTMS, SP.t1_AfterTMS=BlockAfterTMS(SP.voies_,SP.numvoie, \
        SP.blocksize,SP.srate,SP.temps,SP.ThresholdAfterTMS,SP.deltaAfterTMS)
        print "Ok..."
        return

    def on_open_Traitements_Filtre(self):
        c=Tfilter()
        if c.edit():
            SP.alphamin=c.AlphaMin
            SP.alphamax = c.AlphaMax
        else:
            exit(3)
    #-----------------------------------------------------------------------------
    #     calcul coef. du  filtre passe bande
    #-----------------------------------------------------------------------------
        sizet_BeforeTMS=len(SP.t_BeforeTMS)
        sizet_AfterTMS=len(SP.t_AfterTMS)
        SP.bn=coefPassBand(SP.alphamin, SP.alphamax, SP.srate) #calcul coeffs.
        for loop in range(SP.nbblock):
            signal_BeforeTMS=SP.M_BeforeTMS[:,loop]  # extraction d un bloc dans la ligne des essais
            signal_AfterTMS=SP.M_AfterTMS[:,loop]
            #
            filtered_BeforeTMS = []
            filtered_AfterTMS = []
            filtered_BeforeTMS.append(sc.convolve(SP.bn, signal_BeforeTMS)) # filter the signal by convolving the signal with filter coefficients
            filtered_AfterTMS.append(sc.convolve(SP.bn, signal_AfterTMS)) # filter the signal by convolving the signal with filter coefficients
#--------------------------------------------------------------------
#   filtre avant TMS
#--------------------------------------------------------------------
            for i in xrange(0, len(filtered_BeforeTMS)):
                y_p_BeforeTMS = filtered_BeforeTMS[i]
#--------------------------------------------------------------------
#   filtre apres TMS
#--------------------------------------------------------------------
            for i in xrange(0, len(filtered_AfterTMS)):
                y_p_AfterTMS = filtered_AfterTMS[i]
            y_p_BeforeTMS=np.array(y_p_BeforeTMS)
            y_p_AfterTMS=np.array(y_p_AfterTMS)
#--------------------------------------------------------------------
#   mise a jour du block
#--------------------------------------------------------------------
            SP.M_BeforeTMS[:,loop]=y_p_BeforeTMS[0:sizet_BeforeTMS]
            SP.M_AfterTMS[:,loop]=y_p_AfterTMS[0:sizet_AfterTMS]
        return

    def on_open_Traitements_FFT(self):
        p=Tfft()
        if p.edit():
            SP.nbpFFT=p.nbpFFT
            SP.freq_visu=p.freq_visu
        else:
            exit(5)
        SP.freq_BeforeTMS,SP.M_FFT_BeforeTMS=BlockFFT(SP.M_BeforeTMS,SP.nbpFFT,SP.srate,SP.freq_visu)
        SP.freq_AfterTMS,SP.M_FFT_AfterTMS=BlockFFT(SP.M_AfterTMS,SP.nbpFFT,SP.srate,SP.freq_visu)
        print "Fin culcul FFT..."
        return

    def on_open_Traitements_ICA(self):
        pass
        return

    def on_open_Traitements_Ondelette(self):
#-----------------------------------------------------------------------------
#            beguinning of wavelets
#-----------------------------------------------------------------------------
        w= TParamOndelette()
        if w.edit():
            WV.f_start=w.f_start
            WV.f_stop=w.f_stop
            WV.deltafreq=w.deltafreq
        else:
            exit(4)
        f0=2.
        scales = f0/np.arange(WV.f_start,WV.f_stop,WV.deltafreq)*int(SP.srate)
        U=len(scales)
        V_b= len(SP.t_BeforeTMS)
        V_a= len(SP.t_AfterTMS)
#--------------------------------------------------------------------
#   initialise taille des buffers ondelettes
#--------------------------------------------------------------------
        WV.WSUM_BeforeTMS=np.zeros((U, V_b), dtype=np.float)
        WV.WSUM_AfterTMS=np.zeros((U, V_a), dtype=np.float)
#-----------------------------------------------------------------------------
#  start of the loop over all blocs
#-----------------------------------------------------------------------------
        count=0.     # compteur de boucles
        for loop in range(SP.nbblock):   # debut boucle ondelette
            print ".",
            signal_BeforeTMS=SP.M_BeforeTMS[:,loop]  # extraction d un bloc dans la ligne des essais
            signal_AfterTMS=SP.M_AfterTMS[:,loop]
#-----------------------------------------------------------------------------
#   wavelets of Morlet(before et after)
#-----------------------------------------------------------------------------
            # complexe , module , phase
            WC_BeforeTMS,WM_BeforeTMS,Wphase_BeforeTMS=create_wavelet(signal_BeforeTMS,SP.srate,WV.f_start,WV.f_stop,WV.deltafreq)
            WC_AfterTMS,WM_AfterTMS,Wphase_AfterTMS=create_wavelet(signal_AfterTMS,SP.srate,WV.f_start,WV.f_stop,WV.deltafreq)
#-----------------------------------------------------------------------------
#   somme des modules
#-----------------------------------------------------------------------------
            WV.WSUM_BeforeTMS=WV.WSUM_BeforeTMS + WM_BeforeTMS
            WV.WSUM_AfterTMS=WV.WSUM_AfterTMS + WM_AfterTMS
            count=count+1.
        print "\r\nfin du calcul...\n"
#-----------------------------------------------------------------------------
#   calcul of the average over all blocs
#-----------------------------------------------------------------------------
        WV.WSUM_BeforeTMS=WV.WSUM_BeforeTMS/(count)
        WV.WSUM_AfterTMS=WV.WSUM_AfterTMS/(count)
        window.on_open_Visualisations_Ondelette()
        return

    def on_open_Traitements_ITC(self):
        w= TParamOndelette()
        if w.edit():
            WV.f_start=w.f_start
            WV.f_stop=w.f_stop
            WV.deltafreq=w.deltafreq
        else:
            exit(4)
        f0=2.
        scales = f0/np.arange(WV.f_start,WV.f_stop,WV.deltafreq)*int(SP.srate)
        U=len(scales)
        V_b= len(SP.t_BeforeTMS)
        V_a= len(SP.t_AfterTMS)

#-----------------------------------------------------------------------------
#  start of the loop over all blocs
#-----------------------------------------------------------------------------
        WV.ITC_BeforeTMS=np.zeros(SP.nbblock, dtype=[ ('module', 'f8'), ('phase', 'f8')]) #tableau ITC before
        WV.ITC_AfterTMS=np.zeros(SP.nbblock, dtype=[ ('module', 'f8'), ('phase', 'f8')]) #tableau ITC before

        for loop in range(SP.nbblock):   # debut boucle ondelette
            print ".",
            signal_BeforeTMS=SP.M_BeforeTMS[:,loop]  # extraction d un bloc dans la ligne des essais
            signal_AfterTMS=SP.M_AfterTMS[:,loop]
#-----------------------------------------------------------------------------
#   wavelets of Morlet(before et after)
#-----------------------------------------------------------------------------
            # complexe , module , phase
            WC_BeforeTMS,WM_BeforeTMS,phase_BeforeTMS=create_wavelet(signal_BeforeTMS,SP.srate,WV.f_start,WV.f_stop,WV.deltafreq)
            WC_AfterTMS,WM_AfterTMS,phase_AfterTMS=create_wavelet(signal_AfterTMS,SP.srate,WV.f_start,WV.f_stop,WV.deltafreq)
#-----------------------------------------------------------------------------
#   calcul des indexs
#-----------------------------------------------------------------------------
            nbptmax=  (WV.f_stop - WV.f_start)/WV.deltafreq
            indfreq = int((SP.fe_BeforeTMS - WV.f_start)*nbptmax/(WV.f_stop - WV.f_start))
            # ITC before TMS
            phase_F_de_t=phase_BeforeTMS[indfreq,:] # une ligne de phase à la frquence d etude
            module_F_de_t=WM_BeforeTMS[indfreq,:] # une ligne de module à la frquence d etude
            # on selectionne une phase au temps de reference
            indphase=int((SP.deltaBeforeTMS - (SP.Ti_BeforeTMS - SP.ThresholdBeforeTMS))*len(phase_F_de_t)/SP.deltaBeforeTMS)
            WV.ITC_BeforeTMS[loop]['module']=sc.square( module_F_de_t[indphase])  # sauvegarde ITC begore
            WV.ITC_BeforeTMS[loop]['phase']=phase_F_de_t[indphase]  # sauvegarde ITC begore
            # ITC after TMS
            phase_F_de_t=phase_AfterTMS[indfreq,:] # une ligne de phase à la frquence d etude
            module_F_de_t=WM_AfterTMS[indfreq,:] # une ligne de module à la frquence d etude
            # on selectionne une phase au temps de reference
            indphase=int((SP.deltaAfterTMS - (SP.Ti_AfterTMS - SP.ThresholdAfterTMS))*len(phase_F_de_t)/SP.deltaAfterTMS)
            WV.ITC_AfterTMS[loop]['module']=sc.square( module_F_de_t[indphase])  # sauvegarde ITC begore
            WV.ITC_AfterTMS[loop]['phase']=phase_F_de_t[indphase]  # sauvegarde ITC begore
        print "\r\nfin du calcul...\n"
        return

    def on_open_Traitements_Select_voie(self):
    #-----------------------------------------------------------------------------
    #      parametre selection de la voie
    #-----------------------------------------------------------------------------
        c=TChannelParameter()
        if c.edit():
            numv=c.channel
            SP.Ti_BeforeTMS= c.Ti_BeforeTMS*1e-3   # temps de reference avant TMS en s
            SP.Ti_AfterTMS= c.Ti_AfterTMS*1e-3   # temps de reference apres la TMS en s
            SP.fe_BeforeTMS=c.fe_BeforeTMS    #freq. etude
        else:
            exit(3)
        SP.numvoie=numv-1

        #original
        SP.voie_analyse=SP.voies[SP.numvoie,:,:]  # recupere la voie a etudier originale
        SP.voie_analyse=SP.voie_analyse.transpose()
        #traitee
        SP.voie_analyse_=SP.voies_[SP.numvoie,:,:]  # recupere la voie a etudier traitee
        SP.voie_analyse_=SP.voie_analyse_.transpose()
        return

    def on_open_Traitements_Correlation(self):
        pass
        return

    def on_open_Visualisations_Original(self):
        close(1)
        close(2)
        figure(1)
        Z=sinogramme(SP.voies_,SP.numvoie)
        plot(SP.temps,Z)
        title("Blocks signals original",fontsize=9)
        xlabel("Time [s]")
        ylabel("Blocks")
        show()
        figure(2)
        imshow(SP.voie_analyse.transpose(),
                                interpolation='nearest',
                                extent=(0, SP.blocksize, 0, SP.nbblock),
                                origin ='lower' ,
                                aspect = 'normal')
        title("Blocks signals without artefact - above vue",fontsize=9)
        xlabel("Samples")
        ylabel("Blocks")
        show()
        return

    def on_open_Visualisations_Traitees(self):
        close(1)
        close(2)
        figure(1)
        Z=sinogramme(SP.voies_,SP.numvoie)
        plot(SP.temps,Z)
        title("Blocks signals original",fontsize=9)
        xlabel("Time [s]")
        ylabel("Blocks")
        show()
        figure(2)
        imshow(SP.voie_analyse_.transpose(),
                                interpolation='nearest',
                                extent=(0, SP.blocksize, 0, SP.nbblock),
                                origin ='lower' ,
                                aspect = 'normal')
        title("Blocks signals without artefact - above vue",fontsize=9)
        xlabel("Samples")
        ylabel("Blocks")
        show()
        return

    def on_open_Visualisations_Block(self):
        close(3)
        figure(3)
        subplot(121)
        m,n=SP.M_BeforeTMS.shape
        tmin=np.min(SP.t_BeforeTMS)
        tsup=np.max(SP.t_BeforeTMS)
        imshow(SP.M_BeforeTMS.transpose(),
                                interpolation='nearest',
                                extent=(tmin,tsup, 0, n),
                                origin ='lower' ,
                                aspect = 'normal')
        title("Blocks signals before TMS - above vue",fontsize=9)
        ylabel("Blocks voie :"+str(SP.numvoie+1))
        subplot(122)
        m,n=SP.M_AfterTMS.shape
        tmin=np.min(SP.t_AfterTMS)
        tsup=np.max(SP.t_AfterTMS)
        imshow(SP.M_AfterTMS.transpose(),
                                interpolation='nearest',
                                extent=(tmin,tsup, 0, n),
                                origin ='lower' ,
                                aspect = 'normal')
        title("Blocks signals after TMS - above vue",fontsize=9)
        ylabel("Blocks voie :"+str(SP.numvoie+1))
        show()
        return


    def on_open_Visualisations_FFT(self):
        close(3)
        figure(3)
        subplot(121)
        m,n=SP.M_FFT_BeforeTMS.shape
        fmin=np.min(SP.freq_BeforeTMS)
        fsup=np.max(SP.freq_AfterTMS)
        imshow(SP.M_FFT_BeforeTMS.transpose(),
                                interpolation='nearest',
                                extent=(fmin,fsup, 0, n),
                                origin ='lower' ,
                                aspect = 'normal')

        title("FFT Blocks signals before TMS - above vue",fontsize=9)
        ylabel("Blocks voie :"+str(SP.numvoie+1))
        subplot(122)
        m,n=SP.M_FFT_AfterTMS.shape
        fmin=np.min(SP.freq_AfterTMS)
        fsup=np.max(SP.freq_AfterTMS)
        imshow(SP.M_FFT_AfterTMS.transpose(),
                                interpolation='nearest',
                                extent=(fmin,fsup, 0, n),
                                origin ='lower' ,
                                aspect = 'normal')
        title("FFT Blocks signals after TMS - above vue",fontsize=9)
        ylabel("Blocks voie :"+str(SP.numvoie+1))
        show()
        imageName=data.prefixe + "_FFT_" +str(SP.numvoie+1)
        plt.savefig(imageName)
        return

    def on_open_Visualisations_ICA(self):
        pass
        return

    def on_open_Visualisations_Ondelette(self):
#-----------------------------------------------------------------------------
#   affiche moyenne des analyses en ondelette
#-----------------------------------------------------------------------------
        figure(5)
        ax1=subplot(121)
        imb = imshow(WV.WSUM_BeforeTMS,
                                        interpolation='nearest',
                                        extent=(SP.t0_BeforeTMS, SP.t1_BeforeTMS, WV.f_start, WV.f_stop),
                                        origin ='lower' ,
                                        aspect = 'normal')
        title("WT before TMS",fontsize=9)
        xlabel('time [s]')
        ylabel('Freq. [Hz]')
        ax2=subplot(122, sharey=ax1)
        ima = imshow(WV.WSUM_AfterTMS,
                                        interpolation='nearest',
                                        extent=(SP.t0_AfterTMS, SP.t1_AfterTMS, WV.f_start, WV.f_stop),
                                        origin ='lower' ,
                                        aspect = 'normal')
        title("WT after TMS",fontsize=9)
        xlabel('time [s]')
        subplots_adjust(hspace=0.05)
        show()
        imageName=data.prefixe + "_WV_" +str(SP.numvoie+1)
        plt.savefig(imageName)
        return

    def on_open_Visualisations_ITC(self):
    #-----------------------------------------------------------------------------
    # plot of IFC before in polar coordonates of phases and amplitudes for all blocks
    #-----------------------------------------------------------------------------
        close(4)
        figure(4)
        rc('xtick', labelsize=9)
        rc('ytick', labelsize=9)
    #
        ax1=subplot(121, polar=True)
        ax1.plot(WV.ITC_BeforeTMS['phase'], WV.ITC_BeforeTMS['module'], color='#ee8d18', marker='o',ls='none')
        grid(True)
        title("ITC avant TMS", fontsize=9)
        ax2=subplot(122, polar=True)
        ax2.plot(WV.ITC_AfterTMS['phase'], WV.ITC_AfterTMS['module'], color='#ee8d18', marker='o',ls='none')
        grid(True)
        title("ITC apres TMS", fontsize=9)
        xlabel( data.prefixe+"_"+str(SP.numvoie+1))
        show()
        return

    def on_open_Visualisations_Correlation(self):
        pass
        return


    def filtre_all(self):
        SP.bn=coefPassBand(SP.alphamin, SP.alphamax, SP.srate) #calcul coeffs.
        sizet_BeforeTMS=len(SP.t_BeforeTMS)
        sizet_AfterTMS=len(SP.t_AfterTMS)
        for loop in range(SP.nbchannel):
#-----------------------------------------------------------------------------
#     selection block avant TMS
#-----------------------------------------------------------------------------
            SP.M_BeforeTMS,SP.t_BeforeTMS, SP.ind0_BeforeTMS, SP.ind1_BeforeTMS, \
                SP.t0_BeforeTMS, SP.t1_BeforeTMS=BlockBeforeTMS(SP.voies_,\
                loop,SP.blocksize,SP.srate,SP.temps,SP.ThresholdBeforeTMS,SP.deltaBeforeTMS)
            SP.M_AfterTMS,SP.t_AfterTMS, SP.ind0_AfterTMS, SP.ind1_AfterTMS, \
            SP.t0_AfterTMS, SP.t1_AfterTMS=BlockAfterTMS(SP.voies_,loop, \
            SP.blocksize,SP.srate,SP.temps,SP.ThresholdAfterTMS,SP.deltaAfterTMS)
            # boucle sue le nombre de block
            for boucle in range(SP.nbblock):
                signal_BeforeTMS=SP.M_BeforeTMS[:,boucle]  # extraction d un bloc dans la ligne des essais
                signal_AfterTMS=SP.M_AfterTMS[:,boucle]
                #
                filtered_BeforeTMS = []
                filtered_AfterTMS = []
                filtered_BeforeTMS.append(sc.convolve(SP.bn, signal_BeforeTMS)) # filter the signal by convolving the signal with filter coefficients
                filtered_AfterTMS.append(sc.convolve(SP.bn, signal_AfterTMS)) # filter the signal by convolving the signal with filter coefficients
    #--------------------------------------------------------------------
    #   filtre avant TMS
    #--------------------------------------------------------------------
                for i in xrange(0, len(filtered_BeforeTMS)):
                    y_p_BeforeTMS = filtered_BeforeTMS[i]
    #--------------------------------------------------------------------
    #   filtre apres TMS
    #--------------------------------------------------------------------
                for i in xrange(0, len(filtered_AfterTMS)):
                    y_p_AfterTMS = filtered_AfterTMS[i]
                y_p_BeforeTMS=np.array(y_p_BeforeTMS)
                y_p_AfterTMS=np.array(y_p_AfterTMS)
    #--------------------------------------------------------------------
    #   mise a jour du block
    #--------------------------------------------------------------------
                SP.M_BeforeTMS[:,boucle]=y_p_BeforeTMS[0:sizet_BeforeTMS]
                SP.M_AfterTMS[:,boucle]=y_p_AfterTMS[0:sizet_AfterTMS]


    def on_open_Batch_Originaux(self):
        for loop in range(SP.nbchannel):
    #-----------------------------------------------------------------------------
    #     selection block
    #-----------------------------------------------------------------------------
            SP.M_BeforeTMS,SP.t_BeforeTMS, SP.ind0_BeforeTMS, SP.ind1_BeforeTMS, \
                SP.t0_BeforeTMS, SP.t1_BeforeTMS=BlockBeforeTMS(SP.voies_,\
                loop,SP.blocksize,SP.srate,SP.temps,SP.ThresholdBeforeTMS,SP.deltaBeforeTMS)
            SP.M_AfterTMS,SP.t_AfterTMS, SP.ind0_AfterTMS, SP.ind1_AfterTMS, \
            SP.t0_AfterTMS, SP.t1_AfterTMS=BlockAfterTMS(SP.voies_,loop, \
            SP.blocksize,SP.srate,SP.temps,SP.ThresholdAfterTMS,SP.deltaAfterTMS)
    #-----------------------------------------------------------------------------
    #     affichage des block avant et apres
    #-----------------------------------------------------------------------------
            close(3)
            figure(3)
            subplot(121)
            m,n=SP.M_BeforeTMS.shape
            tmin=np.min(SP.t_BeforeTMS)
            tsup=np.max(SP.t_BeforeTMS)
            imshow(SP.M_BeforeTMS.transpose(),
                                    interpolation='nearest',
                                    extent=(tmin,tsup, 0, n),
                                    origin ='lower' ,
                                    aspect = 'normal')
            title("Blocks signals before TMS - above vue",fontsize=9)
            ylabel("Blocks voie :"+str(loop+1))
            subplot(122)
            m,n=SP.M_AfterTMS.shape
            tmin=np.min(SP.t_AfterTMS)
            tsup=np.max(SP.t_AfterTMS)
            imshow(SP.M_AfterTMS.transpose(),
                                    interpolation='nearest',
                                    extent=(tmin,tsup, 0, n),
                                    origin ='lower' ,
                                    aspect = 'normal')
            title("Blocks signals after TMS - above vue",fontsize=9)
            ylabel("Blocks voie :"+str(loop+1))
            show()
            imageName=data.prefixe + "_ORG_" +str(loop+1)
            plt.savefig(imageName)
        return


    def on_open_Batch_Filtre(self):
        window.filtre_all()  #filtre toutes les voies
        print "fin filtre sur toutes les voies.."
        return

    def sort_by_power(self,f,M):
        print f.shape,M.shape
        return

    def on_open_Batch_FFT(self):
        for loop in range(SP.nbchannel):
#-----------------------------------------------------------------------------
#     selection block avant TMS
#-----------------------------------------------------------------------------
            SP.M_BeforeTMS,SP.t_BeforeTMS, SP.ind0_BeforeTMS, SP.ind1_BeforeTMS, \
                SP.t0_BeforeTMS, SP.t1_BeforeTMS=BlockBeforeTMS(SP.voies_,\
                loop,SP.blocksize,SP.srate,SP.temps,SP.ThresholdBeforeTMS,SP.deltaBeforeTMS)
            SP.M_AfterTMS,SP.t_AfterTMS, SP.ind0_AfterTMS, SP.ind1_AfterTMS, \
            SP.t0_AfterTMS, SP.t1_AfterTMS=BlockAfterTMS(SP.voies_,loop, \
            SP.blocksize,SP.srate,SP.temps,SP.ThresholdAfterTMS,SP.deltaAfterTMS)
#calcul FFT
            SP.freq_BeforeTMS,SP.M_FFT_BeforeTMS=BlockFFT(SP.M_BeforeTMS,SP.nbpFFT,SP.srate,SP.freq_visu)
            SP.freq_AfterTMS,SP.M_FFT_AfterTMS=BlockFFT(SP.M_AfterTMS,SP.nbpFFT,SP.srate,SP.freq_visu)
            sort_by_power(SP.freq_BeforeTMS,SP.M_FFT_BeforeTMS)
            SP.numvoie=loop
            window.on_open_Visualisations_FFT()

        return

    def on_open_Batch_Ondelette(self):
        WV.ref_phi_BeforeTMS=sc.zeros((SP.nbchannel,SP.nbblock),dtype='float')
        for loop in range(SP.nbchannel):
#-----------------------------------------------------------------------------
#     selection block avant TMS
#-----------------------------------------------------------------------------
            SP.M_BeforeTMS,SP.t_BeforeTMS, SP.ind0_BeforeTMS, SP.ind1_BeforeTMS, \
                SP.t0_BeforeTMS, SP.t1_BeforeTMS=BlockBeforeTMS(SP.voies_,\
                loop,SP.blocksize,SP.srate,SP.temps,SP.ThresholdBeforeTMS,SP.deltaBeforeTMS)
            SP.M_AfterTMS,SP.t_AfterTMS, SP.ind0_AfterTMS, SP.ind1_AfterTMS, \
            SP.t0_AfterTMS, SP.t1_AfterTMS=BlockAfterTMS(SP.voies_,loop, \
            SP.blocksize,SP.srate,SP.temps,SP.ThresholdAfterTMS,SP.deltaAfterTMS)
            SP.numvoie=loop   # numero de voie qui change
# calcul ondelette
            f0=2.
            scales = f0/np.arange(WV.f_start,WV.f_stop,WV.deltafreq)*int(SP.srate)
            U=len(scales)
            V_b= len(SP.t_BeforeTMS)
            V_a= len(SP.t_AfterTMS)
    #--------------------------------------------------------------------
    #   initialise taille des buffers ondelettes
    #--------------------------------------------------------------------
            WV.WSUM_BeforeTMS=np.zeros((U, V_b), dtype=np.float)
            WV.WSUM_AfterTMS=np.zeros((U, V_a), dtype=np.float)
    #-----------------------------------------------------------------------------
    #  start of the loop over all blocs
    #-----------------------------------------------------------------------------
            count=0.     # compteur de boucles
            for boucle in range(SP.nbblock):   # debut boucle ondelette
                print ".",
                signal_BeforeTMS=SP.M_BeforeTMS[:,boucle]  # extraction d un bloc dans la ligne des essais
                signal_AfterTMS=SP.M_AfterTMS[:,boucle]
    #-----------------------------------------------------------------------------
    #   wavelets of Morlet(before et after)
    #-----------------------------------------------------------------------------
                # complexe , module , phase
                WC_BeforeTMS,WM_BeforeTMS,phase_BeforeTMS=create_wavelet(signal_BeforeTMS,SP.srate,WV.f_start,WV.f_stop,WV.deltafreq)
                WC_AfterTMS,WM_AfterTMS,phase_AfterTMS=create_wavelet(signal_AfterTMS,SP.srate,WV.f_start,WV.f_stop,WV.deltafreq)

    #-----------------------------------------------------------------------------
    #   recherche module et phase pour fe=10 Hz et ti=250 par defaut
    #-----------------------------------------------------------------------------
                nbptmax=  (WV.f_stop - WV.f_start)/WV.deltafreq
                indfreq = int((SP.fe_BeforeTMS - WV.f_start)*nbptmax/(WV.f_stop - WV.f_start))
                phase_F_de_t=phase_BeforeTMS[indfreq,:] # une ligne de phase à la frquence d etude
                module_F_de_t=WM_BeforeTMS[indfreq,:] # une ligne de module à la frquence d etude
                # on selectionne une phase au temps de reference
                indphase=int((SP.deltaBeforeTMS - (SP.Ti_BeforeTMS - SP.ThresholdBeforeTMS))*len(phase_F_de_t)/SP.deltaBeforeTMS)
                print "indphase=",indphase
                # creer tableau des phases
                WV.ref_phi_BeforeTMS[loop,boucle]=phase_F_de_t[indphase]
    #-----------------------------------------------------------------------------
    #   somme des modules
    #-----------------------------------------------------------------------------
                WV.WSUM_BeforeTMS=WV.WSUM_BeforeTMS + WM_BeforeTMS
                WV.WSUM_AfterTMS=WV.WSUM_AfterTMS + WM_AfterTMS
                count=count+1.
            print "\r\nfin du calcul...\n"
    #-----------------------------------------------------------------------------
    #   calcul of the average over all blocs
    #-----------------------------------------------------------------------------
            WV.WSUM_BeforeTMS=WV.WSUM_BeforeTMS/(count)
            WV.WSUM_AfterTMS=WV.WSUM_AfterTMS/(count)
            window.on_open_Visualisations_Ondelette()
        print "fin traitement batch ondelette..."
    #-----------------------------------------------------------------------------
    #   tri des phases
    #-----------------------------------------------------------------------------
        WV.index_phase=sc.zeros((SP.nbchannel,SP.nbblock))
        for loop in range(SP.nbchannel):
            # on travaille sur WV.ref_phi_BeforeTMS[loop,:]
            tri_phase=np.zeros(SP.nbblock, dtype=[ ('indice', 'i4'), ('valeur', 'f8')]) #tableau temporaire de rangement des phases
            for boucle in range(SP.nbblock):
                tri_phase['indice'][boucle]=boucle
                tri_phase['valeur'][boucle]=WV.ref_phi_BeforeTMS[loop,boucle]
            tri_phase=sc.sort(tri_phase,order='valeur')
            WV.index_phase[loop,:]=tri_phase['indice']

        return

    def on_open_Batch_tri_Phase(self):
        for loop in range(SP.nbchannel):
    #-----------------------------------------------------------------------------
    #     selection block
    #-----------------------------------------------------------------------------
            SP.M_BeforeTMS,SP.t_BeforeTMS, SP.ind0_BeforeTMS, SP.ind1_BeforeTMS, \
                SP.t0_BeforeTMS, SP.t1_BeforeTMS=BlockBeforeTMS(SP.voies_,\
                loop,SP.blocksize,SP.srate,SP.temps,SP.ThresholdBeforeTMS,SP.deltaBeforeTMS)
            SP.M_AfterTMS,SP.t_AfterTMS, SP.ind0_AfterTMS, SP.ind1_AfterTMS, \
            SP.t0_AfterTMS, SP.t1_AfterTMS=BlockAfterTMS(SP.voies_,loop, \
            SP.blocksize,SP.srate,SP.temps,SP.ThresholdAfterTMS,SP.deltaAfterTMS)
            m,n=SP.M_BeforeTMS.shape    #dimension de la matrice
            ind=WV.index_phase[loop,:]    # recup table des indexs triés
            M_BeforeTMS_tri=SP.M_BeforeTMS.copy() #juste une copie pour garder la dimension
            for k in range(n):
                M_BeforeTMS_tri[:,k]=SP.M_BeforeTMS[:,ind[k]]
            SP.M_BeforeTMS=M_BeforeTMS_tri.copy()
            # after
            m,n=SP.M_AfterTMS.shape    #dimension de la matrice
            M_AfterTMS_tri=SP.M_AfterTMS.copy() #juste une copie pour garder la dimension
            for k in range(n):
                M_AfterTMS_tri[:,k]=SP.M_AfterTMS[:,ind[k]]
            SP.M_AfterTMS=M_AfterTMS_tri.copy()
    #-----------------------------------------------------------------------------
    #     affichage des block avant et apres
    #-----------------------------------------------------------------------------
            close(3)
            figure(3)
            subplot(121)
            m,n=SP.M_BeforeTMS.shape
            tmin=np.min(SP.t_BeforeTMS)
            tsup=np.max(SP.t_BeforeTMS)
            imshow(SP.M_BeforeTMS.transpose(),
                                    interpolation='nearest',
                                    extent=(tmin,tsup, 0, n),
                                    origin ='lower' ,
                                    aspect = 'normal')
            title("Blocks signals before TMS - above vue",fontsize=9)
            ylabel("Blocks voie :"+str(loop+1))
            subplot(122)
            m,n=SP.M_AfterTMS.shape
            tmin=np.min(SP.t_AfterTMS)
            tsup=np.max(SP.t_AfterTMS)
            imshow(SP.M_AfterTMS.transpose(),
                                    interpolation='nearest',
                                    extent=(tmin,tsup, 0, n),
                                    origin ='lower' ,
                                    aspect = 'normal')
            title("Blocks signals after TMS - above vue",fontsize=9)
            ylabel("Blocks voie :"+str(loop+1))
            show()
            imageName=data.prefixe + "_TRI_PHASE_" +str(loop+1)
            plt.savefig(imageName)
        return

    def on_open_Batch_ITC(self):
        WV.ref_phi_BeforeTMS=sc.zeros((SP.nbchannel,SP.nbblock),dtype='float')
        for loop in range(SP.nbchannel):
#-----------------------------------------------------------------------------
#     selection block avant TMS
#-----------------------------------------------------------------------------
            SP.M_BeforeTMS,SP.t_BeforeTMS, SP.ind0_BeforeTMS, SP.ind1_BeforeTMS, \
                SP.t0_BeforeTMS, SP.t1_BeforeTMS=BlockBeforeTMS(SP.voies_,\
                loop,SP.blocksize,SP.srate,SP.temps,SP.ThresholdBeforeTMS,SP.deltaBeforeTMS)
            SP.M_AfterTMS,SP.t_AfterTMS, SP.ind0_AfterTMS, SP.ind1_AfterTMS, \
            SP.t0_AfterTMS, SP.t1_AfterTMS=BlockAfterTMS(SP.voies_,loop, \
            SP.blocksize,SP.srate,SP.temps,SP.ThresholdAfterTMS,SP.deltaAfterTMS)
            SP.numvoie=loop   # numero de voie qui change
# calcul ondelette
            f0=2.
            scales = f0/np.arange(WV.f_start,WV.f_stop,WV.deltafreq)*int(SP.srate)
            U=len(scales)
            V_b= len(SP.t_BeforeTMS)
            V_a= len(SP.t_AfterTMS)
    #-----------------------------------------------------------------------------
    #  start of the loop over all blocs
    #-----------------------------------------------------------------------------
            WV.ITC_BeforeTMS=np.zeros(SP.nbblock, dtype=[ ('module', 'f8'), ('phase', 'f8')]) #tableau ITC before
            WV.ITC_AfterTMS=np.zeros(SP.nbblock, dtype=[ ('module', 'f8'), ('phase', 'f8')]) #tableau ITC before
            for boucle in range(SP.nbblock):   # debut boucle ondelette
                print ".",
                signal_BeforeTMS=SP.M_BeforeTMS[:,boucle]  # extraction d un bloc dans la ligne des essais
                signal_AfterTMS=SP.M_AfterTMS[:,boucle]
    #-----------------------------------------------------------------------------
    #   wavelets of Morlet(before et after)
    #-----------------------------------------------------------------------------
                # complexe , module , phase
                WC_BeforeTMS,WM_BeforeTMS,phase_BeforeTMS=create_wavelet(signal_BeforeTMS,SP.srate,WV.f_start,WV.f_stop,WV.deltafreq)
                WC_AfterTMS,WM_AfterTMS,phase_AfterTMS=create_wavelet(signal_AfterTMS,SP.srate,WV.f_start,WV.f_stop,WV.deltafreq)

    #-----------------------------------------------------------------------------
    #   calcul des indexs
    #-----------------------------------------------------------------------------
                nbptmax=  (WV.f_stop - WV.f_start)/WV.deltafreq
                indfreq = int((SP.fe_BeforeTMS - WV.f_start)*nbptmax/(WV.f_stop - WV.f_start))
                # ITC before TMS
                phase_F_de_t=phase_BeforeTMS[indfreq,:] # une ligne de phase à la frquence d etude
                module_F_de_t=WM_BeforeTMS[indfreq,:] # une ligne de module à la frquence d etude
                # on selectionne une phase au temps de reference
                indphase=int((SP.deltaBeforeTMS - (SP.Ti_BeforeTMS - SP.ThresholdBeforeTMS))*len(phase_F_de_t)/SP.deltaBeforeTMS)
                WV.ITC_BeforeTMS[boucle]['module']= sc.square( module_F_de_t[indphase])  # sauvegarde ITC begore
                WV.ITC_BeforeTMS[boucle]['phase']=phase_F_de_t[indphase]  # sauvegarde ITC begore
                # ITC after TMS
                phase_F_de_t=phase_AfterTMS[indfreq,:] # une ligne de phase à la frquence d etude
                module_F_de_t=WM_AfterTMS[indfreq,:] # une ligne de module à la frquence d etude
                # on selectionne une phase au temps de reference
                indphase=int((SP.deltaAfterTMS - (SP.Ti_AfterTMS - SP.ThresholdAfterTMS))*len(phase_F_de_t)/SP.deltaAfterTMS)
                WV.ITC_AfterTMS[boucle]['module']=sc.square( module_F_de_t[indphase])  # sauvegarde ITC begore
                WV.ITC_AfterTMS[boucle]['phase']=phase_F_de_t[indphase]  # sauvegarde ITC begore
            print "loop = ",loop,"\r\nfin du calcul...\n"
            SP.numvoie
            window.on_open_Visualisations_ITC()

            imageName=data.prefixe + "_ITC_" +str(loop+1)
            plt.savefig(imageName)
        print "fin traitement batch ITC..."
        return

    def on_open_About_Struct_data(self):
        print "filename=",data.filename
        print "prefixe=",data.prefixe
        return

    def on_open_About_Struct_Signal(self):
        print "nb. channel =" ,SP.nbchannel
        print "nbblock=",SP.nbblock
        print "blocksize=",SP.blocksize
        print "voies=",SP.voies.shape
        print "voies_=",SP.voies_.shape
        print "srate=",SP.srate
        print "dt=",SP.dt
        print "temps=",SP.temps.shape
        print "t_sav=",SP.t_sav.shape
        print "ThresholdBeforeTMS=",SP.ThresholdBeforeTMS
        print "ThresholdAfterTMS=",SP.ThresholdAfterTMS
        print "numvoie=",SP.numvoie
        print "voie_analyse=",SP.voie_analyse.shape
        print "voie_analyse_=",SP.voie_analyse_.shape
        print "deltaBeforeTMS =",SP.deltaBeforeTMS
        print "deltaAfterTMS=",SP.deltaAfterTMS
        print "M_BeforeTMS=",SP.M_BeforeTMS.shape
        print "t_BeforeTMS=",SP.t_BeforeTMS.shape
        print "ind0_BeforeTMS=",SP.ind0_BeforeTMS
        print "ind1_BeforeTMS=",SP.ind1_BeforeTMS
        print "t0_BeforeTMS=",SP.t0_BeforeTMS
        print "t1_BeforeTMS=",SP.t1_BeforeTMS
        print "M_AfterTMS=",SP.M_AfterTMS.shape
        print "t_AfterTMS=",SP.t_AfterTMS.shape
        print "ind0_AfterTMS=",SP.ind0_AfterTMS
        print "ind1_AfterTMS=",SP.ind1_AfterTMS
        print "t0_AfterTMS=",SP.t0_AfterTMS
        print "t1_AfterTMS=",SP.t1_AfterTMS
        print "Alpha min=",SP.alphamin
        print "Alpha max=",SP.alphamax
        print "nb. pt. FFT =",SP.nbpFFT
        print "ref_phi_BeforeTMS=", WV.ref_phi_BeforeTMS.shape
        print "index_phase=",WV.index_phase.shape
        return

if __name__ == '__main__':
    from PyQt4.QtGui import QApplication
    import sys
    app = QApplication(sys.argv)
    data=Tdata()    # creation classe de donnees
    SP=TsignalParameters()  # classe des parametres des signaux
    WV=Tondelette()   # classe pour les ondelettes
    SP.srate=2500
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

